package com.taobaolite.history;

import com.taobaolite.item.Item;
import com.taobaolite.item.ItemRepository;
import com.taobaolite.user.User;
import com.taobaolite.user.UserRepository;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.sql.Timestamp;
import java.util.List;

@Aspect
@Component
public class HistoryAOP {

    private final HistoryRepository historyRepo;
    private final ItemRepository itemRepo;
    private final UserRepository userRepo;

    @Autowired
    public HistoryAOP(HistoryRepository historyRepo, ItemRepository itemRepo, UserRepository userRepo) {
        this.historyRepo = historyRepo;
        this.userRepo = userRepo;
        this.itemRepo = itemRepo;
    }

    // execution(方法修饰符(可选) 返回类型 方法名 参数 异常模式(可选)) ，可以使用通配符匹配字符，*可以匹配任意字符。
    @Pointcut("execution(public * com.taobaolite.item.ItemService.getItem(..))")
    public void historyAspect(){}

    @AfterReturning("historyAspect()")
    @Transactional
    public void doAfterReturning(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        if (args[1] == null) {
            return;
        }
        Item item = itemRepo.findById(Long.valueOf(String.valueOf(args[0])))
                .orElseThrow();
        User user = userRepo.findById(Long.valueOf(String.valueOf(args[1])))
                .orElseThrow();
        List<History> historys = historyRepo.findByGuestId(user.getUserId());

        for (History history : historys) {
            if (history.getItem().equals(item)) {
                if (new Timestamp(System.currentTimeMillis()).getTime()
                        - history.getHistoryPK().getTime().getTime() < 10000 ) {
                    historyRepo.delete(history);
                }
            }
        }
//        historyRepo.save(new History(
//                new Timestamp(System.currentTimeMillis()),
//                user,
//                false,
//                item
//        ));

        historyRepo.save(new History(
                new Timestamp(System.currentTimeMillis()),
                user,
                false,
                item
        ));
    }

}
